package com.crv.ci.publish;

import com.crv.ci.model.*;
import com.crv.ci.mq.producer.IProducerService;
import com.crv.ci.service.IAgentService;
import com.crv.ci.service.ITaskParamService;
import com.crv.ci.service.ITaskService;
import com.crv.ci.service.ITemplateShellService;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.*;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by shurrik on 2016/1/7.
 */

@SuppressWarnings("unchecked")
@Service("TaskManager")
public class TaskManager {

    @Autowired
    private IProducerService producerService;
    @Autowired
    private ITaskService taskService;
    @Autowired
    private IAgentService agentService;
    @Autowired
    private ITemplateShellService templateShellService;
    @Autowired
    private ITaskParamService taskParamService;

    public void create(Job job,Agent agent,AgentNode agentNode,TemplateShell templateShell)
    {
        //创建任务
        //创建任务节点
        //创建任务参数
    }

    public void run(Job job,Task task) throws Exception {
        TemplateShell templateShell = templateShellService.fetch(job.getTemplateId());
        List<TaskParam> params = taskParamService.findList("taskId", task.getId());

        String msg = this.getCmd(templateShell,params);
        Agent agent = agentService.fetch(task.getAgentId());
        //发送消息
        producerService.sendMessage(agent.getIp(),msg);

        //将任务状态置为开始执行

    }

    private String getCmd(TemplateShell templateShell,List<TaskParam> params) throws Exception {

        Configuration cfg = new Configuration();
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        String templateContent=templateShell.getContent();
        stringLoader.putTemplate("myShell",templateContent);

        cfg.setTemplateLoader(stringLoader);

        Template template = cfg.getTemplate("myShell","utf-8");
        Map<String,Object> model = new HashMap();
        for(TaskParam param:params)
        {
            model.put(param.getTplKey(),param.getTplVal());
        }

        StringWriter writer = new StringWriter();
        template.process(model, writer);
        return writer.toString();
    }
}
